<template>
  <div class="content">
    <div class="cloud-header">
      <h2>门店管理</h2>
    </div>
    <div class="cloud-body">
      <div class="cloud-shop-body">
        <h3 class="frm_title">基本信息<span class="frm_title_dec">基本信息提交后不可修改</span></h3>
        <Form :label-width="110" mode="single" :model="menus" ref="form" showErrorTip :rules="validRules">
          <FormItem label="地址">
            <div style="height: 300px">
              <Map @change="getMapInfo" />
            </div>
          </FormItem>
          <FormItem label="门店名称" prop="business_name">
            <input type="text" v-width="392" v-model="menus.business_name" />
            <p class="frm_tips">门店名不得含有区域地址信息（如，北京市XXX公司）</p>
          </FormItem>
          <FormItem label="分店名称" prop="branch_name">
            <input type="text" v-width="392" v-model="menus.branch_name" />
            <p class="frm_tips">分店名不得含有区域地址信息（如，“北京国贸店”中的“北京”）</p>
          </FormItem>
          <FormItem label="营业执照" prop="sid">
            <input type="text" v-width="392" v-model="menus.sid" />
            <p class="frm_tips">请输入营业执照上统一社会机构代码</p>
          </FormItem>
          <FormItem label="类目" prop="categories">
            <type v-model="menus.categories" />
          </FormItem>
          <h3 class="frm_title">服务信息<span class="frm_title_dec">该部分为公共编辑信息，每个添加了该门店的商户均可提交修改意见，并在审核后选择性采纳</span></h3>
          <FormItem label="门店图片" prop="photo_list">
            <Upload v-model="menus.photo_list" mode="wechat" :limit="9"></Upload>
            <p class="frm_tips">图片大小不宜超过200KB</p>
          </FormItem>
          <FormItem label="电话" prop="telephone">
            <input type="text" v-width="392" v-model="menus.telephone" />
            <p class="frm_tips">固定电话需加区号；区号、分机号均用“-”连接</p>
          </FormItem>
          <FormItem label="人均价格(选填)" prop="avg_price">
            <NumberInput type="text" v-width="392" v-model="menus.avg_price" />
            <p class="frm_tips">大于零的整数，须如实填写，默认单位为人民币</p>
          </FormItem>
          <FormItem label="营业时间" prop="open_time">
            <input type="text" v-width="392" v-model="menus.open_time" />
            <p class="frm_tips">如，10:00-21:00(必须为24小时制)</p>
          </FormItem>
          <FormItem label="推荐(选填)" prop="recommend">
            <textarea v-width="392" v-model="menus.recommend"></textarea>
            <p class="frm_tips">如，推荐菜，推荐景点，推荐房间</p>
          </FormItem>
          <FormItem label="特色服务" prop="special">
            <textarea v-width="392" v-model="menus.special"></textarea>
            <p class="frm_tips">如，免费停车，WiFi</p>
          </FormItem>
          <FormItem label="简介(选填)" prop="introduction">
            <textarea v-width="392" v-model="menus.introduction"></textarea>
            <p class="frm_tips">对品牌或门店的简要介绍</p>
          </FormItem>
          <FormItem label="门店列表" prop="shop_list">
            <!--   <textarea v-width="392" v-model="menus.shop_list"></textarea> -->
            <p class="frm_tips">关联的门店列表</p>
          </FormItem>
          <FormItem label="支付等级">
            <input type="text" v-width="130" v-model="pay_level.one" placeholder="一档金额" />&nbsp;&nbsp;&nbsp;
            <input type="text" v-width="130" v-model="pay_level.two" placeholder="二档金额" />&nbsp;&nbsp;&nbsp;
            <input type="text" v-width="130" v-model="pay_level.three" placeholder="三档金额" />
            <p class="frm_tips">支付不同的金额，获得不同等级优惠券，输入档位金额，例如 100,500,2000 表示100以内一个档位 100-500一个档位...</p>
          </FormItem>
          <h3 class="frm_title"></h3>
          <FormItem>
            <Button color="primary" :loading="isLoading" @click="submit">提交</Button>&nbsp;&nbsp;&nbsp;
          </FormItem>
        </Form>
      </div>
    </div>
  </div>
</template>
<script type="text/javascript">
import Map from '@/components/map.vue';
import Upload from '@/components/upload.vue';
import typeSelect from '@/components/typeSelect/index.vue';
import Type from '@/components/type.vue';
import { setPio } from '@/utils';
export default {
  components: {
    Map,
    Upload,
    Type,
    typeSelect
  },
  data() {
    return {
      isLoading: false,
      menus: {
        'sid': "",
        'business_name': '',
        'branch_name': '',
        'categories': [],
        'province': '',
        'city': '',
        'district': '',
        'address': '',
        'telephone': '',
        'longitude': '',
        'latitude': '',
        'avg_price': '',
        'open_time': '',
        'recommend': '',
        'special': '',
        'introduction': '',
        'photo_list': [],
        'shop_list': []
      },
      pay_level: { one: '', two: '', three: '' },
      poiList: [],
      poiInfo: {},
      validRules: {
        rules: {
          business_name: {
            maxLen: 15
          },
          branch_name: {
            maxLen: 20
          },
          avg_price: {
            type: 'number',
            valid(prop, parent, data) {
              if (prop <= 0) {
                return '必须大于0'
              }
              return true;
            }
          },
          introduction: {
            maxLen: 300
          },
          telephone: {
            valid: {
              pattern: /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/,
              message: '请输入正确的手机号或固定电话'
            }
          }
        },
        required: ['business_name', 'branch_name', 'categories', 'telephone', 'sid','open_time','special']
      }
    };
  },
  /**
   * 页面渲染前
   * @return {[type]} [description]
   */
  created() {

  },
  /**
   * 计算属性
   * @type {Object}
   */
  computed: {

  },
  /**
   * 页面加载执行
   * @return {[type]} [description]
   */
  mounted() {
    this.getPoiList();
  },
  methods: {
    /**
     * 表单提交
     * @return {[type]} [description]
     */
    submit() {
      //支付等级处理
      let one = parseFloat(this.pay_level.one)
      let two = parseFloat(this.pay_level.two)
      let three = parseFloat(this.pay_level.three)
      if (one && two && three) {
        if (one < two && two < three) {
          this.menus.pay_level = one + '|' + two + '|' + three
        } else {
          this.$Message.error('档位金额不规范');
          return false
        }
      } else {
        this.$Message.error('请添加支付等级');
        return false
      }

      this.isLoading = true;
      let validResult = this.$refs.form.valid();
      if (validResult.result) {

        if (this.checkPoiName()) {
          this.$Confirm('是否尝试导入门店？', '您添加的门店已经存在').then(() => {
            this.importPoi();
          }).catch(() => {
            this.$Message.error('取消');
          });
          return;
        }
        this.addData(this.menus);
      } else {
        this.isLoading = false;
      }
    },
    /**
     * 获取门店列表
     * @return {[type]} [description]
     */
    getPoiList() {
      this.$cloud.wechat().getPoiList().then(data => {
        if (data.errcode === 0) {
          console.log("获取微信门店立碑", data.business_list)
          this.poiList = data.business_list;
        }
      }).catch(error => {
        console.log("getPoiList", error)
        this.$Message.error('微信请求超时');
      });
    },
    /**
     * 检查门店是否存在
     * @return {[type]} [description]
     */
    checkPoiName() {
      if (this.poiList.length) {
        for (let index in this.poiList) {
          let item = this.poiList[index];
          if (item.base_info.business_name == this.menus.business_name && item.base_info.branch_name == this.menus.branch_name) {
            this.poiInfo = item;
            return true;
          }
        }
      }
      return false;
    },
    /**
     * 添加门店数据
     */
    addData(postData, is_import = false) {
      console.log("查看数据", postData);
      if (postData.province && postData.longitude) {
        postData.point = [parseFloat(postData.longitude), parseFloat(postData.latitude)]
        console.log('postData', JSON.stringify(postData));
        this.$cloud.name('shop').insert(postData, true).then(res => {
          this.isLoading = false;
          if (!is_import) {
            this.addPoi(res);
          } else {
            this.$Message('导入店铺成功');
            this.$refs.form.resetValid();
            setTimeout(() => {
              this.$router.push('/merchant/shop');
            }, 1000);
          }
        }).catch(error => {
          log(error);
          this.isLoading = false;
          this.$Message.error(error.data.msg);
        });
      } else {
        this.isLoading = false;
        this.$Message.error('请通过地图导入门店城市信息');
      }
    },
    /**
     * 是否导入该门店
     * @return {[type]} [description]
     */
    importPoi() {
      this.addData(this.poiInfo.base_info, true);
    },
    /**
     * 微信添加门店
     * @param {[type]} data [description]
     */
    addPoi(data) {
      data = setPio(data);
      this.$cloud.wechat().addPoi(data).then(res => {
        console.log('res', res);
        this.updateShop(data._id, res.poi_id);
      }).catch(error => {
        console.log('添加失败则删除数据', error);
        this.delData(data._id);
      });
    },
    /**
     * 添加门店数据
     */
    delData(id) {
      console.log('this.menus', JSON.stringify(this.menus));
      this.$cloud.name('shop').where({ _id: id }).delete().then(res => {
        console.log('数据库操作', res);
        this.$Message.error('创建门店失败');
      }).catch(error => {
        log(error);
        this.$Message.error('异常操作');
      });
    },
    /**
     * 更新门店数据
     * @return {[type]} [description]
     */
    updateShop(id, poi_id) {
      this.$cloud.name('shop').where({ _id: id }).update({ poi_id: poi_id }).then(res => {
        console.log('更新数据库操作', res);
        this.$Message('创建店铺成功');
        this.isLoading = false;
        this.$refs.form.resetValid();
        setTimeout(() => {
          this.$router.push('/merchant/shop');
        }, 1000);
      }).catch(error => {
        log(error);
        this.delData(id);
      });
    },
    /**
     * 获取信息
     * @param  {[type]} data [description]
     * @return {[type]}      [description]
     */
    getMapInfo(data) {
      let categories = [];
      if (data.category) {
        let category = data.category.split(':');
        categories = [category.join(',')];
      }
      let business_name = "";
      let branch_name = "";
      //正则处理导入的门店信息-分店信息
      let nameArray = data.name.match(/(.+?)\((.+?)\)/i);
      if (nameArray) {
        business_name = nameArray[1];
        branch_name = nameArray[2];
      }
      this.menus.business_name = business_name || data.name;
      this.menus.branch_name = branch_name;
      this.menus.categories = data.categories;
      this.menus.province = data.province;
      this.menus.city = data.city;
      this.menus.district = data.district;
      this.menus.address = data.address;
      this.menus.telephone = data.phone;
      this.menus.longitude = String(data.latLng.lng);
      this.menus.latitude = String(data.latLng.lat);
    }
  }
};

</script>
<style lang="less" scoped="true">
.cloud-shop-body {
  margin: 0 15px;

  .frm_tips {
    width: auto;
    padding-top: 4px;
    width: 300px;
    color: #9a9a9a;
  }

  .frm_title {
    font-size: 14px;
    height: 32px;
    line-height: 32px;
    border-bottom: 1px solid #e7e7eb;
    margin-bottom: 25px;
    font-weight: normal;

    .frm_title_dec {
      color: #9a9a9a;
      margin-left: 1em;
      font-weight: normal;
    }
  }

}

</style>
